#include "musicServer.h"
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <cstring>
#include <json-c/json.h>
#include "stdTcpService.h"
#define BUFFER_SIZE 128
#include <jsoncpp/json/json.h>
#include <string>
#include "stdSqliteDataBase.h"
#include "stdDataBase.h"
#include "stdShared.h"

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <fstream>
#include <iostream>

#include "base64.h"

MusicServer::MusicServer(const StdTcpSocket &clientSocket) : m_clientSocket(clientSocket)
{
    // song["打上花火"] = "/home/lvguanzhong/code/268SystemProgram/FrameWork/musicSet/打上花火.mp3";
    // song["反方向的钟"] = "/home/lvguanzhong/code/268SystemProgram/FrameWork/musicSet/反方向的钟.mp3";
    sqlite = new stdSqliteDataBase();
    sqlite->connect("./test.db");
}

MusicServer::~MusicServer()
{
}

void MusicServer::handleRegisterInfo(const std::string &info)
{

#if 0
    int ret = 0;
    std::cout << "Register info:" << info << std::endl;
    // 解析 JSON 数据
    json_object *jsonObj = json_tokener_parse(info.c_str());
    // 提取待注册信息的用户名
    const char *username = json_object_get_string(json_object_object_get(jsonObj, "username"));

    const char *path = "./info.txt";
    int fd = open(path, O_RDWR | O_CREAT | O_APPEND, 0644);
    if (fd == -1)
    {
        perror("open error!");
        exit(-1);
    }

    char buf[BUFFER_SIZE] = {0};

    // 提取已经存在的用户信息
    while (true)
    {
        int readBytes = read(fd, buf, strlen(info.c_str()));
        if (readBytes == 0)
        {
            close(fd);
            return ;
        }
        else
        {
            memset(buf, 0, sizeof(buf));
            json_object *jsonObj1 = json_tokener_parse(buf);
            const char *username1 = json_object_get_string(json_object_object_get(jsonObj, "username"));
            if (strcmp(username, username1) == 0)
            {
                std::cout << "exits" << std::endl;
                m_clientSocket.sendMessage("exit");
                close(fd);
                return;
            }
        }
    }
    ret = write(fd, info.c_str(), strlen(info.c_str()));
    if (ret == -1)
    {
        perror("wirte error!");
        exit(-1);
    }
    m_clientSocket.sendMessage("注册成功");

    close(fd);
#endif

#if 1
    Json::Value root;
    Json::CharReaderBuilder reader;

    // 解析Json字符串
    std::istringstream s(info);
    Json::parseFromStream(reader, s, &root, nullptr);
    std::string username = root["username"].asString();
    std::string passwd = root["passwd"].asString();

    if (userExit(username) == true)
    {
        // m_clientSocket.sendMessage("用户已存在");
    }
    else
    {
        StdDataBase *db = new stdSqliteDataBase;
        db->connect("./test.db");
        // 写入数据库
        char buffer[256] = {0};
        sprintf(buffer, "INSERT INTO COMPANY(username,passwd) VALUES('%s','%s');", username.c_str(), passwd.c_str());
        std::cout << buffer << std::endl;
        db->execute(buffer);
        // m_clientSocket.sendMessage("注册完成");
        db->close();
    }

    /* 创建一个json对象 */
    json_object *jsonObj = json_object_new_object();
    json_object_object_add(jsonObj, "type", json_object_new_int(REGISTER));
    json_object_object_add(jsonObj, "username", json_object_new_string("ON_SUCCESS"));
    json_object_object_add(jsonObj, "passwd", json_object_new_string("注册成功"));

    const char *jsonStr = json_object_to_json_string(jsonObj);

    std::cout << jsonStr << std::endl;
    m_clientSocket.sendMessage(jsonStr);
    // std::cout << "账号注册成功！" << std::endl;

#endif
}

void MusicServer::handleLogininInfo(const std::string &info)
{
    std::cout << "Loginin info:" << info << std::endl;
    /* 创建一个json对象 */
    json_object *jsonObj = json_object_new_object();
    json_object_object_add(jsonObj, "type", json_object_new_int(LOGIN));
    json_object_object_add(jsonObj, "status", json_object_new_string("ON_SUCCESS"));
    json_object_object_add(jsonObj, "passwd", json_object_new_string("注册成功"));

    const char *jsonStr = json_object_to_json_string(jsonObj);

    std::cout << jsonStr << std::endl;
    m_clientSocket.sendMessage(jsonStr);
}

// 根据文件路径获得文件的内容
std::string MusicServer::readMusicInfo(const std::string &filepath)
{
    std::ifstream ifs(filepath, std::ios::in | std::ios::binary);
    if (ifs.is_open() == true)
    {
        // 获取文件大小
        ifs.seekg(0, std::ios::end);
        size_t size = ifs.tellg();
        std::cout<<"song size:"<<size<<std::endl;
        ifs.seekg(0, std::ios::beg);
        // 读取文件内容
        std::string buffer(size, '\0');
        ifs.read(&buffer[0], size);
        ifs.close();
        return buffer;
    }
    else
    {
        std::cout<<"文件打开失败"<<std::endl;
        return "";
    }

    // int fd = open(filepath.c_str(), O_RDONLY);

    // struct stat fileinfo;
    // memset(&fileinfo, 0, sizeof(fileinfo));
    // stat(filepath.c_str(), &fileinfo);
    // char *filedata = (char *)malloc(sizeof(char) * fileinfo.st_size);
    // read(fd, filedata, fileinfo.st_size);
    // close(fd);
    // return filedata;
}

void MusicServer::handleDownLoadMusic(const std::string &data)
{

    /* 创建一个json对象 */
    Json::Value root;
    Json::CharReaderBuilder reader;
    std::istringstream s(data);
    Json::parseFromStream(reader, s, &root, nullptr);
    std::string musicName = root["musicName"].asString();

    /* 创建一个json对象 */
    json_object *jsonObj = json_object_new_object();
    json_object_object_add(jsonObj, "type", json_object_new_int(DOWNLOAD_MUSIC));

    std::cout << "download:" << musicName << std::endl;
    std::string musicContent = "";
    std::string encodeMusicContent = "";
    std::string sql = "select songpath from MUSIC where songname = '" + musicName + "';";
    std::cout << "sql:" << sql << std::endl;
    // 返回歌曲路径
    QueryResult result = sqlite->query(sql);
    std::string songpath = "";
    if (result.datas.size() == 0)
    {
        // 未找到
        json_object_object_add(jsonObj, "status", json_object_new_string("ON_FAIL"));
        json_object_object_add(jsonObj, "reason", json_object_new_string("未找到对应歌曲"));
    }
    else
    {
        songpath =  result.datas[0][0];

        std::cout << "歌曲路径:"<<songpath << std::endl;
        musicContent = readMusicInfo(songpath);


        if (musicContent.size() != 0)
        {
            encodeMusicContent = base64_encode((reinterpret_cast<const unsigned char *>(musicContent.c_str())), musicContent.size());
        }

        json_object_object_add(jsonObj, "status", json_object_new_string("ON_SUCCESS"));
        json_object_object_add(jsonObj, "reason", json_object_new_string("下载成功"));
    }
    json_object_object_add(jsonObj, "content", json_object_new_string(encodeMusicContent.c_str()));

   //content中包含了歌曲的大小和内容数据

    const char *jsonStr = json_object_to_json_string(jsonObj);
    std::cout<<strlen(jsonStr)<<std::endl;
    //std::cout << jsonStr << std::endl;
    m_clientSocket.sendMessage(jsonStr);
}

void MusicServer::handleSearchMusic(const std::string &data)
{
    /* 创建一个json对象 */
    Json::Value root;
    Json::CharReaderBuilder reader;
    std::istringstream s(data);
    Json::parseFromStream(reader, s, &root, nullptr);
    std::string musicName = root["musicName"].asString();

    /* 创建一个json对象 */
    json_object *jsonObj = json_object_new_object();
    json_object_object_add(jsonObj, "type", json_object_new_int(SEARCH_MUSIC));

    
    std::string sql = "select songname from MUSIC where songname = '" + musicName + "';";
    
    // 返回歌曲路径
    QueryResult result = sqlite->query(sql);
    std::string name = "";
    if (result.datas.size() == 0)
    {
        // 未找到
        json_object_object_add(jsonObj, "status", json_object_new_string("ON_FAIL"));
        json_object_object_add(jsonObj, "reason", json_object_new_string("未找到对应歌曲"));
    }
    else
    {
        name =  result.datas[0][0];
        json_object_object_add(jsonObj, "status", json_object_new_string("ON_SUCCESS"));
        json_object_object_add(jsonObj, "reason", json_object_new_string("下载成功"));
    }
    json_object_object_add(jsonObj, "name", json_object_new_string(name.c_str()));

   //content中包含了歌曲的大小和内容数据

    const char *jsonStr = json_object_to_json_string(jsonObj);
    m_clientSocket.sendMessage(jsonStr);


}

bool MusicServer::userExit(const std::string &username)
{
    // StdDataBase *db = new stdSqliteDataBase;
    // QueryResult result;

    // char buffer[256] = {0};
    // sprintf(buffer, "select * from COMPANY where username='%s';", username.c_str());
    // std::cout<<buffer<<std::endl;
    // db->connect("./test.db");
    // result = db->query(buffer);
    // if (result.datas.size() == 0)
    // {
    //     std::cout << "未找到" << std::endl;
    //     return false;
    // }
    // std::cout << "找到" << std::endl;
    // db->close();

    // return true;

    // 使用智能指针管理数据库对象
    std::unique_ptr<StdDataBase> db = std::make_unique<stdSqliteDataBase>();
    QueryResult result;

    // 使用 snprintf 替代 sprintf，防止缓冲区溢出
    char buffer[256] = {0};
    snprintf(buffer, sizeof(buffer), "select * from COMPANY where username='%s';", username.c_str());

    std::cout << buffer << std::endl;

    // 连接数据库
    if (!db->connect("./test.db"))
    {
        std::cerr << "连接数据库失败" << std::endl;
        return false;
    }

    // 执行查询
    result = db->query(buffer);
    std::cout << result.datas.size() << std::endl;
    if (result.datas.size() == 1)
    {
        std::cout << "未找到" << std::endl;
        db->close();
        return false;
    }
    else
    {
        std::cout << "找到" << std::endl;
        db->close();
        // 由于使用了智能指针，db 会在作用域结束时自动调用 close()，无需手动关闭
        return true;
    }
}
